import axios from 'axios'
import { Toast } from 'vant'
import { getToken } from '@/utils/validate.js'
import errorCode from '@/utils/errorCode'

const request = axios.create({
  timeout: 20 * 1000,
  responseType: 'json',
  headers: { 'content-type': 'application/json;charset=UTF-8' },
  baseURL: process.env.VUE_APP_BASE_URL,
  withCredentials: false
})

// 请求拦截
request.interceptors.request.use(config => {
  const token = getToken()
  if (token) {
    config.headers['Authorization'] = 'Bearer ' + token
  } else {
    // 返回登录
  }
  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// 响应拦截
request.interceptors.response.use(response => {
  console.log(response, 1111111111111)
  const res = response.data
  // 未设置状态码则默认成功状态
  const code = res.errno + '' || response.status
  // 获取错误信息
  const msg = res.errmsg || errorCode[code] || errorCode['default']
  if (code && code.substring(0, 4) === '3004') {
    // wx.removeStorageSync('token');
    // wx.removeStorageSync('tokenHead');
    // wx.removeStorageSync('openId');
    // wx.navigateTo({
    //   url: '/pages/login/index'
    // });
    // 重新登陆
    Toast(msg)
  }
  const { data, ok, errmsg } = res
  if (ok) {
    return data || []
  } else {
    res.data
    Toast(errmsg)
    return Promise.reject(errmsg)
  }
},
error => {
  console.log(error, 2222222222222222)
  let { message } = error
  if (message === 'Network Error') {
    message = '网关请求失败'
  } else if (message.includes('timeout')) {
    message = '系统接口请求超时'
  } else if (message.includes('Request failed with status code')) {
    message = '系统接口' + message.substr(message.length - 3) + '异常'
  }
  Toast({
    type: 'html',
    message: message,
    duration: 3 * 1000
  })
  return Promise.reject(error)
}
)

function sendRequest(url, method, requestConfig, type) {
  const transUrl = url.replace(/^\//g, '')
  return function(params) {
    type = type || (method === 'get' ? 'params' : 'data')
    const basic = {
      method,
      url: transUrl,
      [type]: params || {}
    }
    const allConfig = Object.assign(
      {},
      basic,
      requestConfig || {}
    )
    return new Promise((res, rej) => {
      request(allConfig).then(json => {
        res(json)
      })
        .catch(error => {
          rej(error)
        })
    })
  }
}

const getMethod = {
  get: (url, config, type) => sendRequest(url, 'get', config, type),
  post: (url, config, type) => sendRequest(url, 'post', config, type)
}

export default getMethod
